#include "TcpServer.hpp"
#include <memory>
#include "Protocol.hpp"
#include <signal.h>
#include"Daemon.hpp"
using namespace ns_tcpserver;
using namespace ns_protocol;

static void Usage(const std::string process)
{
    std::cout << "\nUsage:" << process << "port\n"
              << std::endl;
}

static Response CalculatorHelp(const Request &req)
{
    Response resp(0, 0,req.x_,req.y_,req.op_);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (req.y_ == 0)
            resp.code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (req.y_ == 0)
            resp.code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}

void Calculator(int sock)
{
    std::string inbuffer;
    while (true)
    {
        // 1.读取数据成功
        bool res = Recv(sock, &inbuffer); // 读到一个请求
        if (!res)
            break;
        // 2.协议解析，保证得到一个完整的报文
        std::string package = Decode(inbuffer);
        if (package.empty())
            continue;
        logMessage(NORMAL,"%s",package.c_str());
        //3.保证该报文是一个完整的报文
        Request req;
        //4.反序列化，字节流->结构化
        req.Deserialize(package); // 反序列化
        //5.业务逻辑
        Response resp = CalculatorHelp(req);
        //6.序列化
        std::string respString = resp.Serialize(); // 对计算结果进行序列化
        //7.添加长度信息，形成一个完整的报文
        respString=Encode(respString);
        //8.send暂时这样写,多路转接再改发送的问题
        Send(sock, respString);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }
    // 一般经验：server在编写的时候，要有较为严谨性的判断逻辑
    // 一般服务器，都是要忽略SIGPIPE信号的，防止在运行中出现非法写入的问题！
    //signal(SIGPIPE, SIG_IGN);//在守护进程中忽略信号
    MyDaemon();
    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindService(Calculator);
    server->Start();

    // Request req(123,456,'+');
    // std::string s=req.Serialize();
    // std::cout<<s<<std::endl;

    // Request temp;
    // temp.Deserialize(s);
    // std::cout<<temp.x_<<std::endl;
    // std::cout<<temp.y_<<std::endl;
    // std::cout<<temp.op_<<std::endl;

    return 0;
}